import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/api.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/setting/section/edit_mater_name.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/event_bus.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class Setting extends StatefulWidget {
  final Map info;
  const Setting({super.key, required this.info});

  @override
  State<StatefulWidget> createState() => _SettingState();

}

class _SettingState extends State<Setting> {
  final GlobalKey<TooltipState> tooltipkey = GlobalKey<TooltipState>();
  Map _info = {};


  void _edit(String name) async {
    String textValue = name;
    taiDialog(
      context: context,
      title: "电表名称",
      onConfirm: (taiContext) {
       
        electricityMeterApi.editElectricityMeter({"electricityMeterId": _info["electricityMeterId"], "name": textValue}).then((value) {
          EasyLoading.showToast("修改成功");
          setState(() {
            _info["name"] = textValue;
           });
          // 发送电表名称更新事件通知
          eventBus.fire(ElectricityMeterEvent(
            'nameChanged', 
            {
              "electricityMeterId": _info["electricityMeterId"],
              "name": textValue,
            }
          ));
          
          Navigator.of(taiContext).pop();
       
       });
      },
      contentPadding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 16),
      child: TextFormField(
        autofocus: true,
        textAlign: TextAlign.center,
        decoration: const InputDecoration(
          hintText: "请输入",
          hintStyle: TextStyle(color: ThemeVars.colorTextTer),
          border: InputBorder.none,
          filled: true,
          fillColor: ThemeVars.colorBackground,
        ),
        initialValue: textValue,
        onChanged: (val) {
          textValue = val;
        },
      ),
    );
  }

  void _remove() async {
    EasyLoading.show();
    await electricityMeterApi.removeElectricityMeter(_info["electricityMeterId"]);
    EasyLoading.dismiss();
    Stacker.pushNamedAndRemoveUntil(Keys.DEVICE_ELECTRICITYMETER, ModalRoute.withName(Keys.DEVICE_ELECTRICITYMETER));
  }

  void _clear() async {
    EasyLoading.show();
    await electricityMeterApi.resetElectricityMeter(_info["electricityMeterId"]);
    EasyLoading.dismiss();
    EasyLoading.showToast("清零成功");
    // 通知更新电表信息
    eventBus.fire(ElectricityMeterEvent(
      'refreshInfo', 
      {
        "electricityMeterId": _info["electricityMeterId"],
      }
    ));
  }

  @override
  void initState() {
    setState(() {
      _info = widget.info;
    });
    super.initState();
  }

  @override
  void didUpdateWidget(covariant Setting oldWidget) {
    setState(() {
      _info = widget.info;
    });
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: Text(_info["name"], style: const TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimary,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: ListView(
        children: [
          // MenuBlock(
          //   borderRadius: BorderRadius.circular(0),
          //   items: [
          //     MenuBlockItem(
          //       text: "",
          //       prefix: Row(
          //         children: [
          //           const Text("电费单价"),
          //           Tooltip(
          //             key: tooltipkey,
          //             decoration: const BoxDecoration(
          //               color: Colors.black54,
          //               borderRadius: BorderRadius.all(Radius.circular(5)),
          //             ),
          //             margin: const EdgeInsets.only(right: 100,left: 15),
          //             triggerMode: TooltipTriggerMode.manual,
          //             preferBelow: true,
          //             message: "电费单价设置请在公寓管理中，电表设置中修改",
          //             child: GestureDetector(
          //               child: const Icon(CupertinoIcons.question_circle),
          //               onTap: () {
          //                 tooltipkey.currentState?.ensureTooltipVisible();
          //               },
          //             ),
          //           ),
          //         ],
          //       ),
          //       showArrow: false,
          //       suffix: const Text("1.0"),
          //     ),
          //   ],
          // ),
          const SizedBox(height: 12,),
          MenuBlock(
            borderRadius: BorderRadius.circular(0),
            items: [
              MenuBlockItem(
                text: "电表类型",
                showArrow: false,
                suffix: Text("${widget.info['type'] == '0' ? '房间' : '公区'}"),
              ),
            ],
          ),
          const SizedBox(height: 12,),
          MenuBlock(
            borderRadius: BorderRadius.circular(0),
            items: [
              MenuBlockItem(
                text: "电表名称",
                suffix: Text(_info["name"]),
                onTap: () {
                  _edit(_info["name"]);
                }
              ),
              MenuBlockItem(
                text: "绑定的房源",
                showArrow: false,
                suffix: Text("${widget.info["roomId"] == null ? '未绑定' : (widget.info["room"]["name"] ?? "--")}"),
              ),
            ],
          ),
          const SizedBox(height: 16,),
          Padding(
            padding: const EdgeInsets.fromLTRB(ThemeVars.paddingPage, 30, ThemeVars.paddingPage, 0),
            child: Button(
              type: ButtonType.dangerOutline,
              child: const Text("清零"),
              onPressed: () {
                _clear();
              },
            )
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(ThemeVars.paddingPage, 30, ThemeVars.paddingPage, 0),
            child: Button(
              type: ButtonType.danger,
              child: const Text("删除"),
              onPressed: () {
                _remove();
              },
            )
          ),
        ],
      ),
    );
  }
}